<!--移动签批->公文详情->发文->流转-->
<template>
	<view>
		<van-popup v-model="showCompo" round position="left" :style="{ width: '100%' }"
			@click-overlay="toClose">
		<van-tree-select height="400" :items="selectPersonData" @click-nav="clickNav" :active-id.sync="activeId"
			:main-active-index.sync="activeIndex" @click-item="clickItem" />

		 <view class="padding-top" v-show="checkUserAll">
       <van-cell title="其他人员" :value="selectUserName" @click="showDrafterSheet" is-link/>
       <drafter :showDrafter="showDrafter" @closeDrafterSheet="closeDrafterSheet"></drafter>
		</view>

		<view class="padding-top-lg padding-bottom-lg">
			<van-row type="flex" justify="space-around">
				<van-col span="10">
					<van-button type="info" round plain hairline block @click="toClose">取消</van-button>
				</van-col>
				<van-col span="10">
					<van-button type="info" round block @click="toSbumit">确定</van-button>
				</van-col>
			</van-row>
		</view>
		</van-popup>

	</view>

</template>

<script>
import drafter from 'pages/admin/components/common/compo-drafter';
	export default {
    components: {
      drafter,
    },
		props: {
			showTrans: {
				type: Boolean,
				default: false
			},
			paramObject:{
				type: Object
			},
      detailObject:{//公文详情数据，调流转接口传参数用
				type:Object
			},
      //列表中获取到的proInstId，收文中proInstId在列表和详情中不一致
      proInstId:{
        type:String,
        default: ''
      }
		},
		watch: {
			showTrans(val){
				this.showCompo = val
			},
      detailObject:{
        handler(nVal, oVal) {
          if(this.util.isNotEmpty(nVal)){
            // 获取左侧数据
            this.getSelectPerson(this.proInstId,nVal.drafterId)
          }
        },
        immediate: true,
        deep: true
      }
		},
		data() {
			return {
				showCompo:false,
				itemsLocal:[],//本处室成员
				activeId: '',//右侧选中项的 id，支持传入数组
        selectIndex:'',//右侧选中的下标
				activeIndex: 0,//左侧选中的下标
        selectPersonData:[],
        selectUserId:'',//选中的人id
        selectUserName:'',//选中的人姓名
        checkUserAll:false,//是否能选其他人
        showDrafter:false,
			}
		},
		methods:{
      //呈报人
      showDrafterSheet() {
        this.showDrafter = true
      },
      //关闭呈报人组件
      closeDrafterSheet(userInfo) {
        //userInfo: {"userId":"4926","userName":"高萌"}
        if(this.util.isNotEmpty(userInfo.userId)){
          this.activeId=''
          this.selectUserId = userInfo.userId
          this.selectUserName = userInfo.userName
        }
        this.showDrafter = false
      },
      //流转选人接口
      getSelectPerson(proInstId,drafterId){
        // console.log("paramObject-流转参数: " + JSON.stringify(this.paramObject));
        this.$http({
          url: this.$http.adornUrl(`/caac/oa/app/getSelectPerson`),
          method: 'get',
          params: this.$http.adornParams({
            'systemKey': this.cache.get('userInfo').systemKey,//固定值
            'systemFlag': this.cache.get('userInfo').systemFlag,//固定值
            'proInstId': proInstId,
            'drafterId': drafterId
          })
        }).then(({data}) => {
          // console.log("=========流转选人接口: " + JSON.stringify(data));
          if(data.code==200){
            this.selectPersonData=[]//置空

            if(this.util.isNotEmpty(data.data.otherTask)){
              this.checkUserAll = data.data.otherTask.initSendInfo.needShowSearch //当前人是否有需要选择其他人
            }else{
              //如果otherTask节点为空，则使用该值进行判断
              if (this.util.isNotEmpty(data.data.checkUserAll)){
                this.checkUserAll = data.data.checkUserAll
              }else{
                this.checkUserAll = false
              }
            }
            //otherTask 节点
            if(this.util.isNotEmpty(data.data.otherTask)){
              Object.keys(data.data.otherTask.nextActivities).forEach((value, key) => {
                let childObj = data.data.otherTask.nextActivities[value]
                let children = []
                if(this.util.isNotEmpty(childObj.resources)){
                  childObj.resources.forEach((childVal,index)=>{
                    children.push({
                      'index':index,
                      'id':key+1+"000"+index,//自定义id，防止重复
                      "text": childVal.orgName,
                      "userId": childVal.orgId.split(':')[1],
                      "actDefId":childVal.actDefId
                    })
                  })
                }
                this.selectPersonData.push({
                  'type':'0',//0-本处室人员和本公文经手人员
                  'id':key,
                  'text':childObj.name,
                  'children':children
                })
              })
            }
            //person 节点
            if(this.util.isNotEmpty(data.data.person)){
              data.data.person.forEach((item,index)=>{
                let children = []
                //children 循环
                if(this.util.isNotEmpty(item.childrens)){
                  item.childrens.forEach((childVal,index2)=>{
                    children.push({
                      'index':index2,
                      'id':index+1+"00"+index2,
                      "text": childVal.name,
                      "userId": childVal.id,
                      "actDefPath":childVal.actDefPath,
                      "transActName":childVal.transActName,
                      "actDefName":childVal.actDefName,
                      "proDefId":childVal.proDefId,
                      "actDefId":childVal.actDefId,
                      "proDirId":childVal.proDirId,
                      "actType":childVal.actType
                    })
                  })
                }
                //如果有id，则调用doTrans，否则则调用 gotoActivity，因为这两种选人走不同的接口
                if(this.util.isNotEmpty(item.id)){
                  this.selectPersonData.push({
                    'type':'1',//0-本处室人员和本公文经手人员
                    'id':item.id,
                    'text':item.name,
                    'children':children
                  })
                }else{
                  this.selectPersonData.push({
                    'type':'0',//0-本处室人员和本公文经手人员
                    'id':item.id,
                    'text':item.name,
                    'children':children
                  })
                }
              })
            }

          }else{
            console.log("流转选人接口出错："+data.message)
          }

        })
      },

			//点击左侧导航时触发
			clickNav(index){
				// this.$toast(index)
				this.activeIndex = index
			},
			//点击右侧选择项时触发
			clickItem(data){
        this.selectUserName = ''//置空其他选人
        this.activeId= data.id//下标
        this.selectIndex = data.index
        //获取选中的用户id
        this.selectUserId= data.userId
			},
			//取消按钮
			toClose() {
				this.$emit('closeTrans', this.showTrans);
			},
			//确定按钮，确定流转
			toSbumit() {
				let nextActivity = this.selectPersonData[this.activeIndex]
				// console.log("nextActivity: " + JSON.stringify(nextActivity));
        if(this.util.isNotEmpty(this.selectUserName)){
          //如果是其他选人则调gotoActivity接口流转
          this.gotoActivity()
        }else{
          //类型，0-本处室人员和本公文经手人员，1-其他
          if(nextActivity.type=='0'){
            // this.$toast('本处室人员')
            this.gotoActivity()
          }else if(nextActivity.type=='1'){
            // this.$toast('liuzhuan')
            this.doTrans()
          }else{
            console.log("未知错误")
          }
        }


			},
			//提交流转
			doTrans(){
				var _this = this
				var nextActivity = this.selectPersonData[this.activeIndex].children[this.selectIndex]
        var actInstId =''
        if(this.util.isEmpty(nextActivity.actInstId)){
          actInstId = "@def:"+ nextActivity.actDefPath
        }else{
          actInstId = nextActivity.actInstId
        }
				this.$httploading({
					//http://39.98.62.88/caac/wfm/ApplicationController/completeWorkitem
          url: this.$http.adornUrl(`/caac/wfm/ApplicationController/completeWorkitem`),
				  method: 'post',
				  params:{
					  systemKey:this.cache.get('userInfo').systemKey,
					  systemFlag:this.cache.get('userInfo').systemFlag,
            data:this.$http.adornData({
              fwForm:this.detailObject,
              wfmData:{
                'configId':_this.paramObject.configId,
                'proDirId': _this.paramObject.proDirId,//发文详情返回的proInstId
                'actDefId': _this.paramObject.actDefId,//
                'proInstId':_this.paramObject.proInstId,
                'actInstId': _this.paramObject.actInstId,//
                'workitemId':_this.paramObject.workitemId,
                'nextActivities':[{
                  'actDefId':nextActivity.actDefId,
                  'actDefName':nextActivity.actDefName,
                  'proDefId':nextActivity.proDefId,
                  'actDefPath':nextActivity.actDefPath,
                  'proDirId':nextActivity.proDirId,
                  'actInstId':actInstId,
                  'participants':'user:'+this.selectUserId,//选择的人员id
                  'selectPersonType':'checkbox',
                  'returnSelect':'false'
                }]
              }
					  })
				  }
				}).then(({data}) => {
					console.log("loadItem===>>: " + JSON.stringify(data));
					if(data.code==200){
						this.$toast('流转成功')
						this.$emit('closeTrans', this.showTrans);//关闭
            // 发送通知
            let linkUrl = this.configUtil.baseUrl + this.configUtil.basePath + "/#/pages/admin/send/index?proInstId=" + this.paramObject.proInstId;
            this.lx.sendMessage(this.cache.get("appType"), this.selectUserId,
                this.detailObject.title, "发文", linkUrl);
						uni.redirectTo({
							url:'/pages/admin/send/signList'
						})
						// _this.$emit('refreshBtnGroup',true)//通知父组件重新加载下边菜单

					}else{
						_this.$toast(data.message+' code:'+data.code)
					}

				})
			},
			//选择本处室人员和本公文经手人员时调用
			gotoActivity(){
				var _this = this
				this.$httploading({
          url: this.$http.adornUrl(`/caac/wfm/ApplicationController/gotoActivity`),
				  method: 'post',
				  params:{
					  systemKey:this.cache.get('userInfo').systemKey,
					  systemFlag:this.cache.get('userInfo').systemFlag,
					   data:this.$http.adornData({
						   wfmData:{
							  'configId':_this.paramObject.configId,
							  'proDirId': _this.paramObject.proDirId,//发文详情返回的proInstId
							  'actDefId': _this.paramObject.actDefId,//
							  'proInstId':_this.paramObject.proInstId,
							  'actInstId': _this.paramObject.actInstId,//
							  'workitemId':_this.paramObject.workitemId,
							  'formData':{
								   fwForm:this.detailObject,//详情
							  },
							  "gotoResourceIds": "user:"+this.selectUserId,
							  'gotoActDefId':'otherTask'
						   },
					 })
				  }
				}).then(({data}) => {
					console.log("本处室、本公文经手人员流转返回结果-->>: " + JSON.stringify(data));
					if(data.code==200){
						_this.$toast('流转成功')
            // 发送通知
            let linkUrl = this.configUtil.baseUrl + this.configUtil.basePath + "/#/pages/admin/send/index?proInstId=" + this.paramObject.proInstId;
            this.lx.sendMessage(this.cache.get("appType"), this.selectUserId,
                this.detailObject.title, "发文", linkUrl);
						uni.redirectTo({
							url:'/pages/admin/send/signList'
						})
					}else{
						_this.$toast(data.message+' code:'+data.code)
					}
				})
			},
		},

	}
</script>

<style>
	/deep/ .van-sidebar-item--select::before {
		background-color: #1989fa;
	}
	/deep/ .van-tree-select__item--active {
		color: #1989fa;
	}
</style>
